import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateStudycontentDto } from './dto/create-studycontent.dto';
import { UpdateStudycontentDto } from './dto/update-studycontent.dto';
import { Studycontentsort } from '../studycontentsort/entities/studycontentsort.entity';
import { Repository } from 'typeorm';
import { Studycontent } from './entities/studycontent.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { PageResultDto, QueryListDto } from 'src/common/dto';
import { StudycontentQueryDto } from './dto/selectone-studycontent.dto';
import { Dept } from 'src/modules/system/dept/entities/dept.entity';
@Injectable()
export class StudycontentService {
  constructor(
    @InjectRepository(Studycontent)
    private StudycontentRepository: Repository<Studycontent>,
  ) {}
  async create(createStudycontentDto: CreateStudycontentDto) {
    const { sortId, department, ...rest } = createStudycontentDto;

    const studycontent = new Studycontent();
    Object.assign(studycontent, rest);

    const sort = new Studycontentsort();
    sort.Id = sortId;
    studycontent.sort = sort;

    const dept = new Dept();
    dept.Id = department;
    studycontent.department = dept;

    studycontent.Deleted = 0;

    await this.StudycontentRepository.save(studycontent);
    return '创建成功';
  }

  async findAll(
    querylistDto: StudycontentQueryDto,
  ): Promise<PageResultDto<Studycontent>> {
    const pageNum = Number(querylistDto.pageNum) || 1;
    const pageSize = Number(querylistDto.pageSize) || 10;
    const keyword = querylistDto.keyword || '';
    const sortId = querylistDto.sortId;
    const source = querylistDto.source;
    const department = querylistDto.department;
    const queryBuilder = this.StudycontentRepository.createQueryBuilder(
      'content',
    )
      .leftJoinAndSelect('content.sort', 'sort')
      .leftJoinAndSelect('content.department', 'department')
      .where('content.Deleted = :deleted', { deleted: 0 });

    // 模糊查询
    if (keyword) {
      queryBuilder.andWhere('(content.Name LIKE :keyword)', {
        keyword: `%${keyword}%`,
      });
    }

    // 按 sortId 筛选
    if (sortId) {
      queryBuilder.andWhere('content.sortId = :sortId', { sortId });
    }

    // 按 source 筛选
    if (source) {
      queryBuilder.andWhere('content.source = :source', { source });
    }
    // 按 department 筛选
    if (department) {
      queryBuilder.andWhere('content.departmentId = :department', {
        department,
      });
    }

    const [data, total] = await queryBuilder
      .skip((pageNum - 1) * pageSize)
      .take(pageSize)
      .orderBy('content.Id', 'DESC')
      .getManyAndCount();

    const result = new PageResultDto<Studycontent>();
    result.data = data;
    result.total = total;
    result.pageNum = pageNum;
    result.pageSize = pageSize;
    return result;
  }

  async findOne(id: number): Promise<[boolean, Studycontent]> {
    const item = await this.StudycontentRepository.findOne({
      where: { Id: String(id), Deleted: 0 },
      relations: ['sort', 'department'],
    });
    if (!item) {
      return [false, new Studycontent()];
    } else {
      return [true, item];
    }
  }

  async update(id: number, updateStudycontentDto: UpdateStudycontentDto) {
    const existing = await this.StudycontentRepository.findOne({
      where: { Id: String(id), Deleted: 0 },
    });
    if (!existing) {
      return [false, '更新失败，用户不存在'];
    }

    // 如果传了新的分类或来源ID，更新关联关系
    if (updateStudycontentDto.sortId) {
      const sort = new Studycontentsort();
      sort.Id = updateStudycontentDto.sortId;
      existing.sort = sort;
    }

    Object.assign(existing, updateStudycontentDto);
    await this.StudycontentRepository.save(existing);
    return [true, '更新成功'];
  }

  async remove(id: number) {
    const item = await this.StudycontentRepository.findOne({
      where: { Id: String(id), Deleted: 0 },
    });

    if (!item) {
      throw new NotFoundException(`ID 为 ${id} 的资源未找到或已删除`);
    }

    item.Deleted = 1;
    await this.StudycontentRepository.save(item);

    return '软删除成功';
  }
}
